package org.jooq.impl;


import org.jooq.Configuration;
import org.jooq.Select;
import org.jooq.SelectQuery;
import org.jooq.Table;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 打破访问限制.
 */
public class JooqVisitor2 {

    public static Field limit_SelectImpl = null;
    public static Field offset_SelectImpl = null;

    static {
        try {
            limit_SelectImpl = SelectImpl.class.getDeclaredField("limit");
            limit_SelectImpl.setAccessible(true);
            offset_SelectImpl = SelectImpl.class.getDeclaredField("offset");
            offset_SelectImpl.setAccessible(true);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取from的表数量
     * @param query
     * @return
     */
    public static List<? extends Table<?>> getSelectFromTableList(SelectQuery<?> query) {
        List<? extends Table<?>> tables = Collections.emptyList();
        if (query instanceof SelectQueryImpl) {
            SelectQueryImpl<?> impl = (SelectQueryImpl<?>) query;
            TableList tl = impl.getFrom();
            if (tl != null) {
                tables = new ArrayList<>(tl);
            }
        }
        return tables;
    }

//    public static Fields<?> getFields(TableImpl<?> impl) {
//        return impl.fields;
//    }


    /**
     * 删除列
     * @param impl
     * @param fields
     */
//    public static void removeFields(TableImpl<?> impl, String... fields) {
//        Fields<?> feds = impl.fields;
//        org.jooq.Field<?>[] oldlFieds = feds.fields();
//        List<org.jooq.Field<?>> list = new ArrayList<>(Arrays.asList(oldlFieds));
//        for (String f : fields) {
//            org.jooq.Field<?> t = feds.field(f);
//            if (t != null) {
//                list.remove(t);
//            }
//        }
//        org.jooq.Field<?>[] newFieds = new org.jooq.Field[list.size()];
//        newFieds = list.toArray(newFieds);
//        feds.fields = newFieds;
//    }


    /**
     * 获取查询总数
     * @param configuration
     * @param query
     * @return
     */
    public static String getCountSql(Configuration configuration, Select<?> query) {
        FetchCount fc = new FetchCount(configuration, query);
        return fc.getSQL();
    }

    public static Number getLimit(Select impl) {
        try {
            return (Number) limit_SelectImpl.get(impl);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static Number getOffset(Select impl) {
        try {
            return (Number) offset_SelectImpl.get(impl);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
